package com.vfa.file;


import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.vfa.vocaburay.R;

import android.content.Context;

import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;






public class FileAdapter {

	private final String MNT_PATH = File.listRoots()[0].toString()+"mnt";
	private final String SDCARD_PATH = MNT_PATH +"/sdcard";
	private ArrayList<FileInfo> mFileInfo;

	private Context mContext;
//	private boolean isCompleted = true;
	private int mNumberOfFileInFolder = 0;
	private String fileExtention = "";	
	public static final String EXTENSION_FOLDER = "folder";
	public static final String EXTENSION_CSV = ".csv";
	public static final String EXTENSION_XML = ".xml";

	public FileAdapter(String extension) {

		mFileInfo = new ArrayList<FileInfo>();
		fileExtention = extension;

	
	}
	



	public FileAdapter(Context context, int i) {
		mContext = context;
		mFileInfo = new ArrayList<FileInfo>();
		getDirSearch("/");
//		getDirSearch(SDCARD_PATH);


	}

	public List<FileInfo> getFileInfos() {
		return mFileInfo;
	}

	public void getDir(String dirPath, int sortType, boolean isHiddenDisplay, boolean isOtherDisplay) {

		File f = new File(dirPath);
		File[] files = f.listFiles();

		mFileInfo.clear();

		for (int i = 0; i < files.length; i++) {
			FileInfo fileinfo = new FileInfo();

			File file = files[i];
			if(fileExtention == EXTENSION_FOLDER )
				
			fileinfo.mFilePath = file.getPath();
			if (file.isFile() && file.getName().endsWith(fileExtention)) {
	
					fileinfo.mFileName = file.getName();
					fileinfo.mFileCount = String.valueOf(file.length()  + " byte");
					fileinfo.mFilePath = file.getPath();
					if (file.getPath().endsWith(EXTENSION_CSV)) {

				    	//fileinfo.mFileDrawable = R.drawable.csv_icon2;
				    	
				    	fileinfo.mFileImageType = R.drawable.csv_icon2;
				    }else 
						if (file.getPath().endsWith(".xml"))
							fileinfo.mFileImageType = R.drawable.xml_icon;
					if ((!isOtherDisplay && ((!file.isDirectory() && !file.isFile()) || !file.canRead())) 
							|| (!isHiddenDisplay && file.isHidden())){}
					else mFileInfo.add(fileinfo);
	
			} 
		}
	}
	
	public Drawable getThumbnail(File image) {

	    BitmapFactory.Options bounds = new BitmapFactory.Options();
	    bounds.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(image.getPath(), bounds);
	    if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
	        return null;

	    int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
	            : bounds.outWidth;

	    BitmapFactory.Options opts = new BitmapFactory.Options();
	    opts.inSampleSize = originalSize / 48;
	    Drawable d = new BitmapDrawable(BitmapFactory.decodeFile(image.getPath(), opts));
	    return d;
	}

	public void getDirSearch(String dirPath) {

		File f = new File(dirPath);
		File[] files = f.listFiles();

		mFileInfo.clear();

		for (int i = 0; i < files.length; i++) {
			FileInfo fileinfo = new FileInfo();

			File file = files[i];
			fileinfo.mFilePath = file.getPath();
			
			if (file.isDirectory() && file.canRead()) {

				int count = file.list().length;
				fileinfo.mFileCount = String.valueOf(count) + " items";
				fileinfo.mFileName = file.getName();
				fileinfo.mFileImageType = R.drawable.folder;
				mFileInfo.add(fileinfo);
			} 
			
		}

	}	
		
	private void sortFile(ArrayList<FileInfo> info, int sortType)
	{

		if (sortType == 0)
		{
			IgnoreCaseComparator c = new IgnoreCaseComparator();
			Collections.sort(info, c);
			
		}else if (sortType == 1)
		{
			
			for (int i = 1; i < info.size(); i++)
			{
				File f = new File(info.get(i).mFilePath);
				if (f.isFile())
				{
					info.add(0,info.get(i));
					info.remove(i+1);
				}
			}


			for (int i = 0; i < info.size(); i++)
			{
				File f = new File(info.get(i).mFilePath);
				if (!f.isDirectory() && !f.isFile()) 
				{
					info.add(info.get(i));
					info.remove(i);		
				}
			}
		}
	}
	
	class IgnoreCaseComparator implements Comparator<FileInfo> {
		  public int compare(FileInfo strA, FileInfo strB) {
		    return strA.mFileName.compareToIgnoreCase(strB.mFileName);
		  }
	}
	
	public ArrayList<File> searchFromDirectory(String filename, String path) {
		ArrayList<File> filelist = new ArrayList<File>();
		filelist.clear();
		searchFiles(filelist, filename, path);

		return filelist;

	}
	
	public void searchFiles(ArrayList<File> filelist, String filename, String path) {
		File file = new File(path);
		
		if (file != null) {
			File[] files = file.listFiles();
			
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					File fileS = files[i];
					
					if (fileS.getName().toLowerCase().contains(filename.toLowerCase())) {
						filelist.add(fileS);
					}
					if (fileS.canRead() && fileS.isDirectory()) {
						searchFiles(filelist, filename, fileS.getPath());
					}
				}
			}
		}
	}

	public Map<String, String> getDetailFile(File file) {
		Map<String, String> mapDetail = new HashMap<String, String>();

		mapDetail.put("Name", file.getName());
		mapDetail.put("Size", getSize(file) + " byte(s)");
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");


		mapDetail.put("Modify", "" + sdf.format(file.lastModified()));
		if (file.isDirectory() && file.canRead()) {
			mapDetail.put("NumberOfFile", "" + file.list().length);
		}
		return mapDetail;
	}

	public long getSize(File file){
		if(file.isFile()){
			return file.length();
		}
		return getFileSize(file);
	}
	
	private long getFileSize(File folder) {
		long foldersize = 0;

		File[] filelist = folder.listFiles();
		if (folder.canRead())
		for (int i = 0; i < filelist.length; i++) {
			if (filelist[i].isDirectory()) {
				foldersize += getFileSize(filelist[i]);
			} else {
				foldersize += filelist[i].length();
			}
		}
		return foldersize;
	}
	
	private int getNumberOfFileInFolder(File folder) {
		int count = 0;

		File[] filelist = folder.listFiles();
		for (int i = 0; i < filelist.length; i++) {
			if (filelist[i].isDirectory()) {
				count += getNumberOfFileInFolder(filelist[i]);
			} else {
				count += 1;
			}
		}
		return count;
	}
	
	
}
